import sys
import cv2
import numpy as np

import sys
import cv2
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget, QPushButton, QHBoxLayout,QSpacerItem,QSizePolicy,QTableView,QHeaderView
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem

from PyQt5.QtWidgets import QTableView

from PyQt5.QtWidgets import QStyledItemDelegate
from PyQt5.QtCore import QSize, Qt
from weather import weather_get

dark_StyleSheet="""  
                       QMainWindow {  
                           background-color: #111F33; /* 黑蓝色背景 */  
                           color: white; /* 文本颜色为白色，以便在黑蓝色背景上可见 */  
                       }  
                        QLabel {  
                                border: 2px solid #888; /* 设置边框宽度、样式和颜色 */  
                                padding: 5px; /* 设置内边距 */  
                                font-size: 14pt; /* 设置字体大小 */  
                                color: white; /* 设置字体颜色为白色 */
                            }  

                       /* 你可以在这里添加更多部件的样式定义 */  
                   """
bright_StyleSheet="""  
                       QMainWindow {  
                           background-color: #F0F0F0; /* 白色背景 */  
                           color: black; /* 文本颜色为黑色，以便在白色背景上可见 */  
                       }  
                       QLabel {  
                                border: 2px solid #888; /* 设置边框宽度、样式和颜色 */  
                                padding: 5px; /* 设置内边距 */  
                                font-size: 14pt; /* 设置字体大小 */  
                                color: black; /* 设置字体颜色为白色 */
                            }  
                       /* 你可以在这里添加更多部件的样式定义 */  
                   """
# ... 其他设置 ...

class VideoWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mode="dark"
        self.initUI()



    def initUI(self):

        self.setWindowTitle('番茄作物检测程序')
        self.setGeometry(300, 100, 1300, 700)
        mainmain_layout=QHBoxLayout()
        self.setLayout(mainmain_layout)
        # 创建主布局
        main_layout = QVBoxLayout()
        vice_layout=QVBoxLayout()
        mainmain_layout.addLayout(main_layout)
        mainmain_layout.addLayout(vice_layout)
        little_layout=QVBoxLayout()
        vice_layout.addLayout(little_layout)

        self.update_theme(self.mode)
        self.weather_label=[]
        weather_data = [
            {"date": "今  天", "weather": "Cloudy", "temp": "22°C"},
            {"date": "明  天 ", "weather": "Rainy", "temp": "20°C"},
            {"date": "后  天", "weather": "Sunny", "temp": "25°C"},
        ]
        # 遍历天气数据并创建标签
        for data in weather_data:
            # 创建天气信息的标签
            weather_label = QLabel(f"{data['date']}: {data['weather']}, {data['temp']}")
            # 设置标签的样式表
            weather_label.setStyleSheet("""  
                        QLabel {  
                           00
                            border: 1px solid #ccc;  
                            border-radius: 5px;  
                            padding: 5px 10px;  
                            margin-right: 10px; /* 右侧外边距 */  
                            font-size: 10pt;  
                        }  
                    """)
            self.weather_label.append(weather_label)
            little_layout.addWidget(weather_label)
        self.updateweather()
        self.weather_timer = QTimer(self)
        self.weather_timer.timeout.connect(self.updateweather)
        self.weather_timer.start(3600000)

        self.model = QStandardItemModel(20, 4, self)  # 0行，2列
        self.model.setHorizontalHeaderLabels(['Time', 'Temper','Co2','Humidty'])

        # 创建视图
        self.tableView = QTableView()
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.setFixedHeight(500)  # 设置表格视图的高度为200像素
        # 添加视图到布局
        little_layout.addWidget(self.tableView)

        # 设置定时器来更新表格数据
        self.table_timer = QTimer(self)
        self.table_timer.timeout.connect(self.updateTable)
        self.table_timer.start(100)

        spacer = QSpacerItem(3, 120, QSizePolicy.Minimum, QSizePolicy.Expanding)
        vice_layout.addItem(spacer)

        # 创建视频显示标签
        self.label = QLabel(self)
        self.label.setFixedSize(600,400)
        main_layout.addWidget(self.label)

        # 创建数据展示框和按键
        data_layout = QHBoxLayout()
        main_layout.addLayout(data_layout)

        # 数据展示框
        self.data_labels = [QLabel(f'Data {i + 1}:', self) for i in range(3)]
        for label in self.data_labels:
            data_layout.addWidget(label)

            # 可以设置标签的最小尺寸，以便它们有足够的空间显示内容
            label.setFixedSize(150,40)
            data_layout.addWidget(label)
        button_layout = QHBoxLayout()
            # 按键
        self.buttons = [QPushButton("Button1"), QPushButton("Button2"),QPushButton("Mode")]
        for button in self.buttons:
            button.setStyleSheet("""  
                            QPushButton {  
                                background-color: #ddd; /* 背景颜色 */  
                                border: 2px solid #888; /* 边框 */  
                                border-radius: 5px; /* 边框圆角 */  
                                color: #333; /* 字体颜色 */  
                                padding: 10px 20px; /* 内边距 */  
                                font-size: 12pt; /* 字体大小 */  
                            }  

                            QPushButton:hover {  
                                background-color: #ccc; /* 鼠标悬停时的背景颜色 */  
                            }  

                            QPushButton:pressed {  
                                background-color: #bbb; /* 按下时的背景颜色 */  
                            }  
                        """)

            button_layout.addWidget(button)
            button.setFixedSize(130, 40)
        self.buttons[0].clicked.connect(self.on_button_clicked1)
        self.buttons[1].clicked.connect(self.on_button_clicked2)
        self.buttons[2].clicked.connect(self.on_button_clicked3)

        main_layout.addLayout(button_layout)


        # data_layout.setSpacing(0)
        data_layout.setContentsMargins(10, 10, 10, 10)
        data_layout.setAlignment(Qt.AlignLeft)
        button_layout.setSpacing(180)
        button_layout.setContentsMargins(10, 10, 10, 10)
        button_layout.setAlignment(Qt.AlignLeft)

        # 设置中央控件和布局
        central_widget = QWidget()
        central_widget.setLayout(mainmain_layout)
        self.setCentralWidget(central_widget)

        self.cap = cv2.VideoCapture('video1.mp4')
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateFrame)
        self.timer.start(30)  # update every 30 ms
        self.net = cv2.dnn.readNet("custom-yolov4-tiny-detector_best.weights", "custom-yolov4-tiny-detector.cfg")
        self.classes = ["tomato"]

        self.layer_names = self.net.getLayerNames()
        self.output_layers = [self.layer_names[i[0] - 1] for i in self.net.getUnconnectedOutLayers()]
        self.colors = np.random.uniform(0, 255, size=(len(self.classes), 3))


    def updateweather(self):
        chaxun=weather_get("郑州")
        self.live_weather,self.for_weather,self.live_temp,self.for_temp,self.for_weather_two,self.for_temp_two=chaxun.get_weather()
        weather_data = [
            {"date": "今  天", "weather": self.live_weather, "temp": self.live_temp},
            {"date": "明  天 ", "weather": self.for_weather, "temp": self.for_temp},
            {"date": "后  天", "weather": self.for_weather_two, "temp": self.for_temp_two},
        ]
        for i, data in enumerate(weather_data):
            # 获取对应的标签（假设它们已经被存储在self.weather_labels列表中）
            weather_label = self.weather_label[i]
            # 更新标签的文本
            weather_label.setText(f"{data['date']}: {data['weather']}, {data['temp']}")

    def updateTable(self):
        # # 这里模拟添加新的数据行到表格中
        # currentTime = "Time {}".format(self.model.rowCount() + 1)
        # currentValue = self.randomValue()
        #
        # newRow = [QStandardItem(currentTime), QStandardItem(str(currentValue))]
        # self.model.appendRow(newRow)
        #
        # # 移除超出一定范围的数据行，以保持表格大小合适（可选）
        # if self.model.rowCount() > 10:
        #     self.model.removeRow(0)
        pass
    def updateFrame(self):
        if self.cap.isOpened():
            # Loading image
            success, img = self.cap.read()
            img = cv2.resize(img, None, fx=0.4, fy=0.4)
            height, width, channels = img.shape

            # Detecting objects
            blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

            self.net.setInput(blob)
            outs = self.net.forward(self.output_layers)

            # Showing informations on the screen
            class_ids = []
            confidences = []
            boxes = []
            for out in outs:

                for detection in out:
                    scores = detection[5:]
                    class_id = np.argmax(scores)
                    confidence = scores[class_id]
                    if confidence > 0.3:
                        # Object detected
                        print(class_id)
                        center_x = int(detection[0] * width)
                        center_y = int(detection[1] * height)
                        w = int(detection[2] * width)
                        h = int(detection[3] * height)

                        # Rectangle coordinates
                        x = int(center_x - w / 2)
                        y = int(center_y - h / 2)

                        boxes.append([x, y, w, h])
                        confidences.append(float(confidence))
                        class_ids.append(class_id)

            indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
            font = cv2.FONT_HERSHEY_PLAIN
            for i in range(len(boxes)):
                if i in indexes:
                    x, y, w, h = boxes[i]
                    label = str(self.classes[class_ids[i]])
                    color = self.colors[class_ids[i]]
                    cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
                    cv2.putText(img, label, (x, y + 30), font, 1, color, 2)
            rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            h, w, ch = rgbImage.shape
            bytesPerLine = ch * w
            convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.label.setPixmap(QPixmap.fromImage(p))
            data1, data2, data3 = self.calculate_data()  # 假设的方法，你需要实现它
            for txt_label, data in zip(self.data_labels, [data1, data2, data3]):
                txt_label.setText(f'Data: {data}')  # 更新数据展示框的文本


    def calculate_data(self):
        #



        return 123, 456, 789

    def on_button_clicked1(self):
       # 添加按键的处理逻辑
        pass
    def on_button_clicked2(self):
       # 添加按键的处理逻辑
        pass

    def on_button_clicked3(self):
        # 添加按键的处理逻辑

        if self.mode=="dark":
            self.mode="bright"
        else:
            self.mode="dark"
        self.update_theme(self.mode);

    def update_theme(self, theme):
        # 根据当前主题更新样式表
        if self.mode == 'dark':
            self.setStyleSheet(dark_StyleSheet)
        elif self.mode == 'bright':
            self.setStyleSheet(bright_StyleSheet)






    def closeEvent(self, event):
        self.cap.release()
        super().closeEvent(event)




if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = VideoWindow()
    ex.show()
    sys.exit(app.exec_())